import distributedObject from '@ohos.data.distributedDataObject';
import deviceManager from '@ohos.distributedDeviceManager';
import { BusinessError } from '@ohos.base';
import distributedKVStore from '@ohos.data.distributedKVStore';
let g_object = null
let dmInstance = null
let kvStore: distributedKVStore.SingleKVStore | null;
let bindParam: Record<string, string | number> = {
  'bindType': 1,
  'targetPkgName': 'com.example.mclanguagerecord',
  'appName': 'com.example.mclanguagerecord',
  'appOperation': '会议沟通',
  'customDescription': '协同沟通会议'
};
const options: distributedKVStore.Options = {
  createIfMissing: true,
  encrypt: false,
  backup: false,
  autoSync: true,
  kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  securityLevel: distributedKVStore.SecurityLevel.S1,
};
// 执行协同办公的相关操作类
export class Collaboration {
  isCollaboration: boolean = false // 开启协同办公的相关交互
  sessionId: string = ''
  creatorInfo = {
    uid: '',
    templateId: '',
    deviceId: ''
  } // 创建者信息
  currentUser = {
    uid: ''
  }
  userList = [] // 系统办公的用户列表
  levelList = []
  constructor() {
    this.isCollaboration = false
    this.userList = []
    this.levelList = []
    this.currentUser = {
      uid: ''
    }
    this.creatorInfo = {
      uid: '',
      templateId: '',
      deviceId: ''
    }
  }

  // 设置分布式数据对象实例
  setDistributedObject (object) {
    g_object = object
  }

  // 开启或者加入协同
  openCollaboration (sessionId, success, error) {
    if (g_object) {
      this.sessionId = sessionId
      g_object.getKVStore(sessionId, options, async (err: BusinessError, store: distributedKVStore.SingleKVStore) => {
        if (err) {
          await g_object.deleteKVStore('com.example.mclanguagerecord', sessionId)
          console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
          this.openCollaboration(sessionId, success, error)
          return;
        }
        console.info("Succeeded in getting KVStore");
        kvStore = store;
        this.isCollaboration = true
        g_object['isCollaboration'] = true
        const KEY_TEST_STRING_ELEMENT = 'is_collaboration';
        // 如果未定义Schema则Value可以传其他符合要求的值。
        const VALUE_TEST_STRING_ELEMENT = 'true';
        try {
          if (kvStore) {
            kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
              if (err !== undefined) {
                console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
                return;
              }
              console.info('Succeeded in putting data.');
              this.syncData()
            });
          }
        } catch (e) {
          let error = e as BusinessError;
          console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
        }
        success()
      })
    }
  }
  // 同步数据
  syncData () {
    // let devManager: deviceManager.DeviceManager;
    try {
      // create deviceManager
      // devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
      // // deviceIds由deviceManager调用getAvailableDeviceListSync方法得到
      // let deviceIds: string[] = [];
      // if (devManager != null) {
      //   let devices = devManager.getAvailableDeviceListSync();
      //   for (let i = 0; i < devices.length; i++) {
      //     deviceIds[i] = devices[i].networkId as string;
      //   }
      // }
      try {
        // 1000表示最大延迟时间为1000ms
        if (kvStore) {
          kvStore.sync(this.userList.map(item => item.networkId), distributedKVStore.SyncMode.PUSH_ONLY, 500);
        }
      } catch (e) {
        let error = e as BusinessError;
        console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
      }

    } catch (err) {
      let error = err as BusinessError;
      console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message);
    }
  }

  // 关闭协同
  closeCollaboration () {
    // g_object['userList'].forEach(item => {
    //   if (item.info !== 'creator') {
    //     dmInstance.unbindTarget(item.deviceId);
    //   }
    // })
    // g_object['creatorInfo'] = {}
    // g_object['isCollaboration'] = false
    // g_object['userList'] = []
    // this.userList = []
    // this.isCollaboration = false
    // g_object.setSessionId(() => {
    //   g_object = null
    // });
    // deviceManager.releaseDeviceManager(dmInstance);
  }

  // 获取创建者信息与模版信息
  getCreatorInfo () {
    // return g_object['creatorInfo']
  }


  // 设置创建者信息与模版信息
  setCreatorInfo (creator_info) {
    // g_object['isCollaboration'] = true
    // g_object['creatorInfo'] = creator_info
    // this.creatorInfo = creator_info
    // this.setCurrentUser(creator_info)
    // this.save(creator_info.deviceId)
    // this.kvStore.put('creator_info', JSON.stringify(creator_info))
  }

  // 設置當前用戶
  setCurrentUser (info) {
    this.currentUser = info
  }

  // 获取所有协同的用户
  getUserList() {
    // return g_object.userList
  }

  // 添加协同用户
  addUser (userInfo) {
    const KEY_TEST_STRING_ELEMENT = 'user_list';
    // const userList = this.userList.map(item => item)
    if (userInfo.info === 'join') {
      // 如果是加入的，则先获取数据，然后在添加
      kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data: string) => {
        if (err !== undefined) {
          console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
          return;
        }
        console.info('Succeeded in putting data.', data);
        this.userList = JSON.parse(data)
        this.userList.push(userInfo)
        this.changeUserList()
      });
    } else {
      this.userList.push(userInfo)
      this.changeUserList()
    }
    // this.userList = userList
    // g_object.userList = this.userList
    // this.save(userInfo.deviceId)
    // 如果未定义Schema则Value可以传其他符合要求的值。

  }

  changeUserList () {
    const KEY_TEST_STRING_ELEMENT = 'user_list';
    const VALUE_TEST_STRING_ELEMENT = JSON.stringify(this.userList);
    try {
      if (kvStore) {
        kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
          if (err !== undefined) {
            console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
            return;
          }
          console.info('Succeeded in putting data.');
          this.syncData()
        });
      }
    } catch (e) {
      let error = e as BusinessError;
      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
    }
  }

  // 删除协同用户
  deleteUser (uid) {
    // // const userList = this.userList.filter(item => item.uid !== uid)
    // // this.userList = userList
    // g_object['userList'] = g_object['userList'].map(item => {
    //   if (uid === item.uid) {
    //     item.isJoin = false
    //     dmInstance.unbindTarget(item.deviceId);
    //   }
    //   return item
    // })
    // // g_object.isCollaboration = false
    // // this.isCollaboration = false
    // this.userList = g_object['userList']
    // // this.save(userInfo.deviceId)
  }

  // 设置锁定信息
  setLockLayerInfo (uid, activeLeveId) {
    // let deviceId = ''
    // g_object['userList'] = g_object['userList'].map(item => {
    //   if(item.uid === uid) {
    //     item.lockLayerId = activeLeveId
    //     // deviceId = item.deviceId
    //   }
    //   return item
    // })
    // this.userList = g_object['userList']
    // this.save(deviceId)
  }

  // 实时同步语音数据
  changeValue (msg: string) {
    const KEY_TEST_STRING_ELEMENT = 'change_value';
    const VALUE_TEST_STRING_ELEMENT = msg;
    try {
      if (kvStore) {
        kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
          if (err !== undefined) {
            console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
            return;
          }
          console.info('Succeeded in putting data.');
          this.syncData()
        });
      }
    } catch (e) {
      let error = e as BusinessError;
      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
    }
  }

  // 改变图层的绘画信息
  setLevelList (levelList) {
    // g_object['levelList'] = levelList
    const KEY_TEST_STRING_ELEMENT = 'change_level_list';
    const VALUE_TEST_STRING_ELEMENT = JSON.stringify(levelList);
    try {
      if (kvStore) {
        kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
          if (err !== undefined) {
            console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
            return;
          }
          console.info('Succeeded in putting data.');
          this.syncData()
        });
      }
    } catch (e) {
      let error = e as BusinessError;
      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
    }
  }

  // 添加信息
  addLevelList (levelList) {
    // g_object['levelList'] = levelList
    const KEY_TEST_STRING_ELEMENT = 'add_level_list';
    const VALUE_TEST_STRING_ELEMENT = JSON.stringify(levelList);
    try {
      if (kvStore) {
        kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
          if (err !== undefined) {
            console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
            return;
          }
          console.info('Succeeded in putting data.');
          this.syncData()
        });
      }
    } catch (e) {
      let error = e as BusinessError;
      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
    }
  }

  // 监听数据变化
  watchDataChange (dataChange?: (list, type) => void, back?: () => void) {
    // g_object.on("change", (sessionId: string, fields: Array<string>) => {
    //   console.info("change" + sessionId);
    //   if (fields != null && fields != undefined) {
    //     for (let index: number = 0; index < fields.length; index++) {
    //       this[fields[index]] = g_object[fields[index]]
    //       // 如果创建者已经下线，则所有用户都要下线处理
    //       if (fields[index] === 'creatorInfo' && !Object.keys(g_object[fields[index]]).length) {
    //         back()
    //       }
    //       // 判断设备是否上线，上线则绑定，下线则退出。只有创建者的才能进行绑定
    //       if (fields[index] === 'userList' && this.currentUser.uid === this.creatorInfo.uid) {
    //         g_object[fields[index]].forEach(item => {
    //           if (item.info !== 'creator') {
    //             if (item.isJoin) {
    //               dmInstance.bindTarget(item.deviceId, bindParam);
    //             } else {
    //               dmInstance.unbindTarget(item.deviceId);
    //             }
    //           }
    //         })
    //       }
    //       // 判断改变如果是图层数据的话，则通知页面需要渲染新的图层信息
    //       if (fields[index] === 'levelList') {
    //         dataChange && dataChange(g_object[fields[index]])
    //       }
    //     }
    //   }
    // });
    kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (data) => {
      console.info(`dataChange callback call data: ${data}`);
      if (data.updateEntries.length) {
        data.updateEntries.forEach(item => {
          if (item.key === 'is_collaboration') {
            this.isCollaboration = item.value.value === 'true'
          }
          if (item.key === 'user_list') {
            this.userList = JSON.parse(item.value.value as string)
          }
          if (item.key === 'change_value') {
            dataChange && dataChange(item.value.value as string, item.key)
            return
          }
          if (['add_level_list', 'change_level_list', 'user_list'].includes(item.key)) {
            dataChange && dataChange(item.value.value, item.key)
          }
        })
      }
    });
  }

  // 监听用户的上线跟下线变化
  watchStatus () {
    // g_object.on("status", (sessionId: string, networkId: string, status: 'online' | 'offline') => {
    //   console.info("status changed " + sessionId + " " + status + " " + networkId);
    // });
  }
}